<template>
  <div class="home">
    <section class="my_header">
      <section @click = "gotoback()" class="my_header_left">
        <i class="icon_style iconfont icon-arrowleft"></i>
        <button class="back">返回</button>
      </section>
      <section class="my_header_center">
        <span>个人信息</span>
      </section>
      <section class="my_header_right">
      </section>
    </section>

    <input type="file" id="fileInput" accept="image/png,image/gif,image/jpeg" ref="fileInput" v-on:change="addImg"/>


    <section class="center">

      <section class="avatar_show">
        <img class="avatar" :src="$store.state.baseImgUrl + $store.state.userInfo.avatar" alt="" id="avatar" @click="uploadClick">
      </section>

      <section class="show_info">
        <section class="item">
          <section class="item_left"><span>昵称</span></section>
          <section class="item_right">
            <input type="text" v-model="userInfo.nick" readonly>
          </section>
        </section>

        <section class="item">
          <section class="item_left"><span>邮箱</span></section>
          <section class="item_right">
            <input type="text" v-model="userInfo.email" readonly>
          </section>
        </section>

        <section class="item">
          <section class="item_left"><span>性别</span></section>
          <section class="item_right">
            <section class="item_radio">
              <section class="radio_item">
                <input type="radio" name="sex" value="0" v-model="userInfo.sex">男
              </section>
              <section class="radio_item">
                <input type="radio" name="sex" value="1" v-model="userInfo.sex">女
              </section>
            </section>
          </section>
        </section>

        <section class="item">
          <section class="item_left"><span>年龄</span></section>
          <section class="item_right">
            <input type="number" number="true" v-model="userInfo.age" placeholder="请输入年龄">
          </section>
        </section>

        <section class="item">
          <section class="item_left"><span>手机号</span></section>
          <section class="item_right">
            <input type="tel" v-model="userInfo.mobile" placeholder="请输入手机号">
          </section>
        </section>

        <section class="item">
          <section class="item_left"><span>生日</span></section>
          <section class="item_right">
            <input type="date" v-model="userInfo.birthday" placeholder="请输入生日">
          </section>
        </section>

        <section class="item">
          <section class="item_left"><span>城市</span></section>
          <section class="item_right">
            <input type="text" v-model="userInfo.city" placeholder="请输入城市">
          </section>
        </section>

        <section class="item">
          <section class="item_left"><span>信息公开</span></section>
          <section class="item_right">
            <section class="item_radio">
              <section class="radio_item">
                <input type="radio" name="show" value="1" v-model="userInfo.show">是
              </section>
              <section class="radio_item">
                <input type="radio" name="show" value="0" v-model="userInfo.show">否
              </section>
            </section>
          </section>
        </section>

        <section class="item">
          <section class="item_left"><span>自我介绍</span></section>
          <section class="item_right">
            <textarea  id="content_input" v-model="userInfo.signature" rows="1" placeholder="请输入自我介绍" style="" @keyup="autoResize()"></textarea>
            <!--<input type="text" v-model="userInfo.city" placeholder="请输入自我介绍">-->
          </section>
        </section>
      </section>

      <button class="btn" @click="update_userInfo">提交</button>
      <button class="btn" @click="logout">登出</button>
    </section>


    <jm-fooder></jm-fooder>
    <alert-tip v-if="showAlert" :showHide="showAlert" @closeTip="closeTip" :alertText="alertText"></alert-tip>


  </div>
</template>

<script>
  import {mapState, mapMutations} from 'vuex'
  import JmFooder from '../../components/footer/Footer';
  import alertTip from '../../components/common/alertTip'
  import CryptoJS from 'crypto-js'
  import Uploader from '../../service/nos-js-sdk';
  import { Toast } from 'mint-ui'


  export default {
    data() {
      return {
        editor: null,
        show: false,  //展示图片
        showLoad: false, //展示加载
        userInfo: null,
        showAlert: false, //显示提示组件
        alertText: null, //提示的内容
      }
    },
    components:{
      alertTip,
      JmFooder
    },
    mounted(){
      this.userInfo = this.$store.state.userInfo;
    },
    watch:{
    },
    computed: {
      //判断手机号码
      rightPhoneNumber: function (){
        return /^1\d{10}$/gi.test(this.userInfo.mobile)
      }
    },
    methods: {
      ...mapMutations([
        'UPDATE_AVATAR',
        'UPDATE_USERINFO',
        'LOGOUT'
      ]),
      gotoback(){
        this.$router.go(-1)
      },
      closeTip(){
        this.showAlert = false;
      },
      uploadClick(){
        document.getElementById("fileInput").click();
      },

      addImg(){
        let fileinput = document.getElementById('fileInput');
        let image = fileinput.files[0];

        let reader = new FileReader();
        reader.readAsBinaryString(image);

        reader.onload = function (e) {
          let name = CryptoJS.MD5(e.target.result).toString()+'.jpg';
          this.uploadImg(image, name);
        }.bind(this)

      },

      async showImg(fileName){
        this.show = true;
        this.showLoad = false;

        let res = null;
        this.userInfo.avatar = fileName;
        await this.axios.put('/v1/user_info', this.userInfo)
          .then(response => {
            res = response.data;
          })
        if (res.success){
          this.UPDATE_AVATAR(fileName);
        }

      },

      uploadImg(image, fileName){
        this.showLoad = true;
        let that = new Uploader();

        let param = {
          bucketName: 'jimikongjian',
          objectName: fileName,
          token: this.getToken(fileName),
          trunkSize: 4 * 1024 * 1024,
        }

        if (image) {
          that.addFile(image, function(curFile){
            console.log(curFile.fileName + ' is added.');
          });
          that.upload(param, function(curFile){
            console.log('File: ' + curFile.fileName + ' is uploaded.');
            this.showImg(fileName);
          }.bind(this));

        }

      },


      //获取上传凭证
      getToken(Object){
        let p = {
          "Bucket" : "jimikongjian",
          "Object" : Object,
          "Expires" : this.$store.state.expiresTime
        }
        let putPolicy = JSON.stringify(p);
        let wordArray = CryptoJS.enc.Utf8.parse(putPolicy);
        let encodedPutPolicy = CryptoJS.enc.Base64.stringify(wordArray);
        let sign = CryptoJS.HmacSHA256(encodedPutPolicy, this.$store.state.accessSecret);
        let encodedSign = CryptoJS.enc.Base64.stringify(sign);
        return "UPLOAD " + this.$store.state.accessKey + ":" + encodedSign + ":" + encodedPutPolicy;
      },

      async update_userInfo(){
            let res = null;
            await this.axios.put('/v1/user_info', this.userInfo)
              .then(response => {
                res = response.data;
              })
            if (res.success){
              let instance = Toast({message: '修改成功', className: 'toast'});
              setTimeout(() => {
                instance.close();
              }, 2000);
              this.UPDATE_USERINFO(this.userInfo);
            }
            if (!res.success){
              let instance = Toast({message: '网络连接失败', className: 'toast'});

              setTimeout(() => {
                instance.close();
              }, 2000);
            }
          },

      logout(){
        this.LOGOUT();
        this.$router.push('login');
      },

      autoResize() {
        let minRows = 1;
        let maxRows = 4;
        let t = document.getElementById("content_input");
        if (t.scrollTop == 0) t.scrollTop = 1;
        while (t.scrollTop == 0) {
          if (t.rows > minRows)
            t.rows--;
          else
            break;
          t.scrollTop = 1;
          if (t.rows < maxRows)
            t.style.overflowY = "hidden";
          if (t.scrollTop > 0) {
            t.rows++;
            break;
          }
        }
        while (t.scrollTop > 0) {
          if (t.rows < maxRows) {
            t.rows++;
            if (t.scrollTop == 0) t.scrollTop = 1;
          }
          else {
            t.style.overflowY = "auto";
            break;
          }
        }
      },

    },
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
  .mint-toast-text{
    font-size: 0.6rem;
  }
  .toast{
    min-width: 20%;
    width: 20%;
    span{
      color: #FFFFFF;
    }
  }
</style>
<style lang="scss" scoped>
  @import '../../style/mixin';
  .my_header{
    background-color: #33CCFF;
    height: 1.5rem;
    display: flex;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    padding-top: 0.2rem;
    z-index: 100;
    .my_header_left{
      flex: 1;
      margin-left: 0.5rem;

      .icon_style{
        font-size: 0.6rem;
        font-weight: bold;
      }

      .back{
        background-color: transparent;
        font-size: 0.65rem;
        margin: 0;
      }
    }
    .my_header_center{
      flex: 2;
      display: flex;
      text-align: center;
      flex-direction: column;
      align-items: center;
      span{

      }
    }
    .my_header_right{
      flex: 1;
      text-align: right;
      margin-right: 0.5rem;
      .icon_style{
        font-size: 0.65rem;
        font-weight: bold;
        position: relative;
        top: -0.06rem;
      }
    }

  }


  .item{
    margin-right: 2rem;
  }


  .center{
    padding-top: 1.5rem;
    padding-bottom: 2rem;
    overflow: hidden;
  }


  .avatar_show{
    width: 100%;
    height: 6rem;
    display: flex;

    .avatar{
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 4rem;
      height: 4rem;
      @include borderRadius(2rem);
      margin: auto auto;
    }

  }
  .show_info{
    .item{
      width: 100%;
      display: flex;
      border-bottom: solid 1px #666;
      margin: 0.1rem;
      padding: 0.1rem;
      overflow: hidden;
      .item_left{
        flex-direction: column;
        flex: 2;

        span{
          display: inline-block;
          width: 100%;
        }
      }
      .item_right{
        flex-direction: column;
        flex: 8;

        textarea{
          background:transparent;
          overflow-y:hidden;
          resize:none;
          width: 100%;
          height: 100%;
          font-size: 0.6rem;
          text-indent: 0.5rem;
        }

        input{
          width: 100%;
          height: 100%;
          font-size: 0.6rem;
          text-indent: 0.5rem;
        }

        .item_radio{
          width: 50%;
          text-align: left;
          display: flex;

          .radio_item{
            flex-direction: column;
            flex: 1;
            font-size: 0.6rem;
            input{
              width: 0.4rem;
              height: 0.4rem;
            }
          }
        }

      }
    }
  }



  .btn{
    margin: 0 auto;
    display: block;
    background-color: #33CCFF;
    width: 9rem;
    height: 1.4rem;
    color: #FFFFFF;
    font-size: 0.5rem;
    font-weight: bold;
    @include borderRadius(0.7rem);
    margin-top: 1rem;
    margin-bottom: 1rem;
  }

</style>
